#include "ExchangeAdapterConfig.h"
#include "RMMSFixAcceptor.h"
#include "DebugUtils.h"
#include "ExchangeAdapterCompiler.h"

RMMS_NS_BEGIN

RMMSFixAcceptor::RMMSFixAcceptor()
{
}

RMMSFixAcceptor::~RMMSFixAcceptor(){}

std::set<FIX::SessionID> RMMSFixAcceptor::InitSession(
	const tstring &cfgfilename)
{
	pSessionSettings = boost::shared_ptr<FIX::SessionSettings>(
		new FIX::SessionSettings(cfgfilename));
	return pSessionSettings->getSessions();
}

int32 RMMSFixAcceptor::Init(void)
{
	try {
		pMsgStoreFactory = boost::shared_ptr<FIX::FileStoreFactory>(
			new FIX::FileStoreFactory(*pSessionSettings.get()));
		pLogFactory = boost::shared_ptr<FIX::FileLogFactory>(
			new FIX::FileLogFactory(*pSessionSettings.get()));
		pAcceptor = boost::shared_ptr<FIX::SocketAcceptor>(
			new FIX::SocketAcceptor(*this,*pMsgStoreFactory.get(),
			*pSessionSettings.get(),*pLogFactory.get()));
	} catch (std::exception& e) {
		DBG_TRACE(("%s",e.what()));
		return -1;
	} catch(...) {
		return -1;
	}

	return 0;
}

void RMMSFixAcceptor::Uninit()
{
	m_seagent.clear();
}

int32 RMMSFixAcceptor::RegisterAgent(const FIX::SessionID &seID,
	IRMMSFixAcceptorAgent *pagent)
{
	if(m_seagent.end() != m_seagent.find(seID))
		return -1;
	m_seagent[seID] = pagent;
	return 0;
}

void RMMSFixAcceptor::UnregisterAgent(const FIX::SessionID &seID)
{
	if(m_seagent.end() != m_seagent.find(seID))
		m_seagent.erase(seID);
}

int32 RMMSFixAcceptor::Start()
{
	try {
		pAcceptor->start();
	} catch(...){
		return -1;
	}
	
	return 0;
}

void RMMSFixAcceptor::Stop(bool force)
{
	pAcceptor->stop(force);
}

int32 RMMSFixAcceptor::SendMsg(FIX::SessionID &seid,FIX::Message &msg)
{
	return FIX::Session::sendToTarget(msg,seid);
}

void RMMSFixAcceptor::onCreate(const FIX::SessionID& /*seID*/){}

void RMMSFixAcceptor::onLogon(const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->OnLogOn();
}

void RMMSFixAcceptor::onLogout(const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->OnLogout();
}

void RMMSFixAcceptor::fromAdmin(const FIX::Message& msg,
	const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->OnRecvAdm(msg);
}

void RMMSFixAcceptor::fromApp(const FIX::Message& msg,
	const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->OnRecvApp(msg);
}

void RMMSFixAcceptor::toAdmin(FIX::Message& msg,
	const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->PreSendAdm(msg);
}

void RMMSFixAcceptor::toApp(FIX::Message& msg,
	const FIX::SessionID& seID)
{
	if(m_seagent.end()!= m_seagent.find(seID))
		m_seagent[seID]->PreSendApp(msg);
}

RMMS_NS_END